<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Jobs\SetOrder;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class Seckill extends Controller
{
    public $redis ;
    //连接redis
    function __construct()
    {
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1',6379);
    }

    //预热库存
    function preheatInventory()
    {
        $data = \App\Models\Seckill::where('seckill_status',1)->get();
        foreach ($data as $k=>$v)
        {
            for ($i=0;$i<$v['seckill_count'];$i++)
            {
                $this->redis->lPush('goods'.$v['id'],1);
            }
            $this->redis->set('start_time_'.$v['id'],$v['start_time'],$v['end_time']-time());
        }
    }

    function secondKill(Request $request)
    {
        $id = 1;
        $goodsId = 5;
        $uid = rand(1,1000000);
        $time = time();
        $startTime = $this->redis->get('start_time_'.$id);
        if(!$startTime)
        {
            return ['code' => 101,'msg' => '活动已结束','data' => null];
        }
        if($time<$startTime)
        {
            return ['code' => 101,'msg' => '活动未开始','data' => null];
        }
        //记录用户购买凭证
        $userKey = 'userKey_'.$uid;
        $userBuy = $this->redis->sIsMember($userKey,$uid);
        if($userBuy)
        {
            return  ['code' => 101,'msg' => '你已经买过了','data' => null];
        }
        $goodsKey = 'goods'.$id;
        $goodsNum = $this->redis->lLen($goodsKey);
        if($goodsNum<=0)
        {
            return ['code' => 101,'msg' => '已经抢光了'];
        }
        try {
            //记录要监听的事务
            $this->redis->watch(array($goodsKey,$userKey));
            //开启事务
            $this->redis->multi();
            $this->redis->rPop($goodsKey);
            //记录用户购买集合
            $this->redis->sAdd($userKey,$uid);
            //执行事务
            $res = $this->redis->exec();
            if(!$res)
            {
                $this->redis->discard();
                return ['code' => 101,'msg' => '抢购失败'];
            }
            SetOrder::dispatch($uid,$goodsId);
            return  ['code' => 200,'msg'=>'抢购成功'];
        }
        catch (\Exception $e)
        {

        }
        dd($time);
    }


}
